package com.test;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONTokener;

import java.util.*;

/**
 * description:
 *
 * @author dyh 创建时间：2018年03月05日
 */
public class MessageParsingUtil {

    private static MessageParsingUtil instance;

    private MessageParsingUtil() {

    }

    public static MessageParsingUtil getInstance() {
        if (null == instance) {
            instance = new MessageParsingUtil();
        }
        return instance;
    }

    public JSONObject getParsing(String jsonStr) {
        JSONObject sourceObj = JSONObject.fromObject(jsonStr).getJSONObject("body");
        JSONObject result = new JSONObject();
        Iterator it = sourceObj.keys();
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            Object json = new JSONTokener(sourceObj.getString(key)).nextValue();
            if (json instanceof JSONObject) {
                result.put(key, json);
            } else if (json instanceof JSONArray) {
                JSONArray ja = (JSONArray) json;
                List<Map> list = JSONArray.toList(ja, new HashMap(), new JsonConfig());
                List<Object> rsList = new ArrayList();
                Iterator<Map> itList = list.iterator();
                int i = 0;
                while (itList.hasNext()) {
                    Map<String, ?> x = itList.next();
                    if (null == x.get(0)) {
                        rsList.add((Map) ja.get(i));
                        i++;
                    }
                }
                result.put("rows", rsList);
            } else {
                result.put(key, json);
            }
        }
        return result;
    }

    public JSONObject getParsingForPage(String jsonStr, String objName) {
        JSONObject sourceObj = JSONObject.fromObject(jsonStr).getJSONObject("body");
        JSONObject result = new JSONObject();
        if (!isNull(sourceObj.getString("page")))
            result.put("pageIndex", sourceObj.get("page"));
        if (!isNull(sourceObj.getString("rows")))
            result.put("pageSize", sourceObj.get("rows"));
        if (!isNull(sourceObj.getString("total")))
            result.put("total", sourceObj.get("total"));
        sourceObj.remove("page");
        sourceObj.remove("rows");
        sourceObj.remove("total");
        Iterator it = sourceObj.keys();
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            Object json = new JSONTokener(sourceObj.getString(key)).nextValue();
            if (json instanceof JSONObject) {
                result.put(key, json);
            } else if (json instanceof JSONArray) {
                JSONArray ja = (JSONArray) json;
                List<Map> list = JSONArray.toList(ja, new HashMap(), new JsonConfig());
                List<Object> rsList = new ArrayList();
                Iterator<Map> itList = list.iterator();
                if (null == objName || "".equals(objName)) {
                    int i = 0;
                    while (itList.hasNext()) {
                        Map<String, ?> x = itList.next();
                        if (null == x.get(0)) {
                            rsList.add((Map) ja.get(i));
                            i++;
                        }
                    }
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, Object> map = list.get(i);
                        Map<String, Object> tbMap = new HashMap(1);
                        Iterator<String> itm = map.keySet().iterator();
                        while (itm.hasNext()) {
                            String mkey = itm.next();
                            if (null == map.get(mkey)) {
                                Map<String, Object> objMap = new HashMap();
                                JSONObject jobj = (JSONObject) ja.get(i);
                                if (jobj.getJSONObject(mkey).isEmpty()) {
                                    tbMap.put(mkey, map.get(mkey));
                                    itm.remove();
                                } else {
                                    objMap.put(objName, ((JSONObject) ja.get(i)).get(mkey));
                                    rsList.add(objMap);
                                }
                            } else {
                                tbMap.put(mkey, map.get(mkey));
                                itm.remove();
                            }
                        }
                        if (!tbMap.isEmpty()) {
                            map.put(objName, tbMap);
                            rsList.add(map);
                        }
                    }
                }
                result.put("rows", rsList);
            }
        }
        return result;
    }

    private boolean isNull(String str) {
        if (str == null) {
            return true;
        } else {
            str = str.trim();
            return str.equals("null") || str.equals("");
        }
    }

    public static void main(String args[]) {
        String str = "{\n" + "  \"header\": {\n" + "    \"requestType\": \"POLICYQUERYLIST\",\n"
                + "    \"responseCode\": \"0000\",\n" + "    \"errorMessage\": \"成功\",\n"
                + "    \"sendTime\": \"2018-03-06 12-01-06\",\n"
                + "    \"orderId\": \"45613465846511465\",\n" + "    \"productName\": \"产品名称\"\n"
                + "  },\n" + "  \"body\": {\n" + "    \"page\": \"2\",\n" + "    \"rows\": \"2\",\n"
                + "    \"total\": \"3\",\n"
                + "    \"infoList\": [{\"pProductInsur\":{\"createTime\":\"2018-03-05 13:21:30\",\"insrncName\":\"太平洋保险\",\"upDownFlag\":\"up\",\"validFlag\":null,\"sysName\":null,\"healthAdvice\":null,\"productType\":null,\"version\":null,\"orgId\":\"4f5213b3dcb740c8abfd9bd5a86368c4\",\"id\":\"9742605b0b724df0bb49982ba52828ce\",\"userOwner\":null,\"versionRemark\":null,\"coverYear\":\"A01\",\"features\":null,\"ageRemark\":\"不限\",\"recomLevel\":null,\"insrncCode\":\"taipingyang\",\"sumAmount\":\"20\",\"modifyTime\":\"2018-03-05 13:24\",\"publishDate\":\"2018-03-05\",\"delStatus\":\"F\",\"subCategory\":null,\"recomFlag\":null,\"productCode\":\"A005\",\"riskCode\":\"0301\",\"mainCategory\":\"03\",\"terminalType\":null,\"feeFlag\":\"T\",\"suitableCrow\":\"不限\",\"productVersion\":null,\"areaFlag\":null,\"createUser\":\"admin\",\"dateRemark\":null,\"modifyUser\":\"admin\",\"longFlag\":null,\"otherRemark\":null,\"defaultPremium\":213,\"subInsureType\":null,\"mainInsureType\":null,\"pageImage\":null,\"productName\":\"人身损害赔偿20万\",\"deptId\":\"f08a18836276444d80130ecbcca2f7a4\"}},{\"pProductInsur\":{\"createTime\":\"2018-03-05 11:57:48\",\"insrncName\":\"中国平安\",\"upDownFlag\":\"down\",\"validFlag\":null,\"sysName\":null,\"healthAdvice\":null,\"productType\":null,\"version\":null,\"orgId\":\"4f5213b3dcb740c8abfd9bd5a86368c4\",\"id\":\"91306dbd9bb041f88899266604702f21\",\"userOwner\":null,\"versionRemark\":null,\"coverYear\":\"A01\",\"features\":\"人身损害赔偿10万人身损害赔偿10万\",\"ageRemark\":\"不限\",\"recomLevel\":null,\"insrncCode\":\"pingan\",\"sumAmount\":\"10\",\"modifyTime\":\"2018-03-05 13:21\",\"publishDate\":null,\"delStatus\":\"F\",\"subCategory\":null,\"recomFlag\":null,\"productCode\":\"A004\",\"riskCode\":\"0301\",\"mainCategory\":\"03\",\"terminalType\":null,\"feeFlag\":\"T\",\"suitableCrow\":\"不限\",\"productVersion\":null,\"areaFlag\":null,\"createUser\":\"admin\",\"dateRemark\":null,\"modifyUser\":\"admin\",\"longFlag\":null,\"otherRemark\":null,\"defaultPremium\":100,\"subInsureType\":null,\"mainInsureType\":null,\"pageImage\":null,\"productName\":\"人身损害赔偿10万\",\"deptId\":\"f08a18836276444d80130ecbcca2f7a4\"}},{\"pProductInsur\":{\"createTime\":\"2018-03-01 13:47:37\",\"insrncName\":\"安心互联网保险\",\"upDownFlag\":\"up\",\"validFlag\":null,\"sysName\":null,\"healthAdvice\":null,\"productType\":null,\"version\":null,\"orgId\":\"4f5213b3dcb740c8abfd9bd5a86368c4\",\"id\":\"4451aa3a120544fa8ee6549628eb0e3c\",\"userOwner\":null,\"versionRemark\":null,\"coverYear\":\"A01\",\"features\":\"50万意外身故保额;100%意外医疗报销;突发性疾病身故保障;\",\"ageRemark\":\"25岁-50岁\",\"recomLevel\":\"start5\",\"insrncCode\":\"anxin\",\"sumAmount\":\"100\",\"modifyTime\":\"2018-03-05 23:12\",\"publishDate\":\"2018-03-01\",\"delStatus\":\"F\",\"subCategory\":null,\"recomFlag\":\"0\",\"productCode\":\"ax100\",\"riskCode\":\"0301\",\"mainCategory\":\"03\",\"terminalType\":null,\"feeFlag\":\"T\",\"suitableCrow\":\"青年\",\"productVersion\":null,\"areaFlag\":null,\"createUser\":\"admin\",\"dateRemark\":null,\"modifyUser\":\"admin\",\"longFlag\":null,\"otherRemark\":null,\"defaultPremium\":100,\"subInsureType\":null,\"mainInsureType\":null,\"pageImage\":null,\"productName\":\"安意保155万综合意外保障计划\",\"deptId\":\"f08a18836276444d80130ecbcca2f7a4\"}}]\n"
                + "  }\n" + "}";

        JSONObject js = MessageParsingUtil.getInstance().getParsingForPage(str, "order");
        System.out.println(js.toString());
        str = "{\n" + "  \"header\": {\n" + "    \"requestType\": \"POLICYQUERYLIST\",\n"
                + "    \"responseCode\": \"0000\",\n" + "    \"errorMessage\": \"成功\",\n"
                + "    \"sendTime\": \"2018-03-06 12-01-06\",\n"
                + "    \"orderId\": \"45613465846511465\",\n" + "    \"productName\": \"产品名称\"\n"
                + "  },\n" + "  \"body\": {\n" + "    \"page\": \"2\",\n" + "    \"rows\": \"2\",\n"
                + "    \"total\": \"3\",\n" + "    \"infoList\": [\n" + "      {\n"
                + "        \"policyNo\": \"1010058776026620000000000\",\n"
                + "        \"appNo\": \"1520308873689\",\n" + "        \"holder\": \"李彦宏\",\n"
                + "        \"insBeginDate\": \"2018-2-19 00:00:00\",\n"
                + "        \"insEndDate\": \"2019-2-18 23:59:59\",\n"
                + "        \"premium\": \"400\",\n" + "        \"amount\": \"100000\"\n"
                + "      },\n" + "      {\n"
                + "        \"policyNo\": \"1010063779745590000000088\",\n"
                + "        \"appNo\": \"1520308873689\",\n" + "        \"holder\": \"李彦宏\",\n"
                + "        \"insBeginDate\": \"2018-11-19 00:00:00\",\n"
                + "        \"insEndDate\": \"2019-11-18 23:59:59\",\n"
                + "        \"premium\": \"400\",\n" + "        \"amount\": \"100000\"\n"
                + "      }\n" + "    ]\n" + "  }\n" + "}";
        js = MessageParsingUtil.getInstance().getParsingForPage(str, "");
        System.out.println(js.toString());
        str = "{\"header\":{\"requestType\":\"POLICYQUERY\",\"from\":\"17100001\",\"sendTime\":\"发送时间\",\"orderId\":\"渠道订单号\",\"isGroup\":\"是否团单\",\"productCode\":\"产品代码\",\"productName\":\"产品名称\"},\n"
                + "\"body\":{\n" + "\t\"order\": {\n" + "\t\t  \"orderId\": \"订单号\",\n"
                + "\t\t  \"applyNum\": \"投保份数\",\n" + "\t\t  \"totalPremium\": \"总保费\",\n"
                + "\t\t  \"totalAmount\": \"总保额\",\n" + "\t\t  \"appTm\": \"投保日期\",\n"
                + "\t\t  \"insBeginDate\": \"保险起期\",\n" + "\t\t  \"insEndDate\": \"保险止期\",\n"
                + "\t\t  \"payOrderNo\": \"预支付订单号\",\n" + "\t\t  \"underwriteFlag\": \"是否核保通过\",\n"
                + "\t\t  \"failReason\": \"核保失败原因\"\n" + "\t\t}\n" + "}}";
        js = MessageParsingUtil.getInstance().getParsing(str);
        System.out.println(js.toString());
    }
}
